<template>
  <div>
    <div class="container">
      <div class="left">
        <h3>发表新攻略</h3>
        <p>分享你的个人游记，让更多人看到哦！</p>
        <el-form ref="form" :model="form">
          <el-form-item>
            <el-input v-model="form.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item class="vue-editor">
            <client-only>
              <vue-editor
                style="width:745px;height:400px"
                useCustomImageHandler
                @image-added="handleImageAdded"
                :editorToolbar="customToolbar"
                v-model="form.content"
              ></vue-editor>
            </client-only>
          </el-form-item>
          <el-form-item label="选择城市">
            <el-autocomplete
              class="inline-input"
              v-model="form.city"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              :trigger-on-focus="false"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item>
            <el-button @click="publish" size="small" type="primary">发布</el-button>或者
            <span @click="draftSave" class="draftSave">保存到草稿</span>
          </el-form-item>
        </el-form>
      </div>
      <div class="right">
        <div class="draft">
          <h3>
            草稿箱 (
            <span>{{$store.state.post.draftList.length}}</span> )
          </h3>
          <div v-for="(item,index) in $store.state.post.draftList" :key="index" class="item">
            <div class="item_l">
              <p>{{item.title}}</p>
              <span>{{mytime}}</span>
            </div>
            <div class="item_r">
              <i @click="edit(index)" class="el-icon-edit"></i>
              <i @click="remove(index)" class="el-icon-delete"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>

import moment from 'moment'
export default {

  data() {
    return {
      form: {
        title: '',
        content: '',
        city: ''
      },
      customToolbar: [
        ['bold', 'italic', 'underline'],
        [{ header: 1 }],
        [{ header: 2 }],
        [{ list: 'ordered' }, { list: 'bullet' }],
        ['image']
      ],
      cityList: [],
      isClient: false
    }
  },
  mounted() {
  },
  methods: {
    // 添加图片上传功能
    handleImageAdded(files, Editor, cursorLocation, resetUploader) {
      var formData = new FormData()
      formData.append('files', files)
      this.$axios({
        url: '/upload',
        method: 'POST',
        data: formData
      }).then(res => {
        console.log(res)
        //上传图片成功
        let url = res.config.baseURL + res.data[0].url
        // 将图片插入相应的位置
        Editor.insertEmbed(cursorLocation, 'image', url)
        // 重新加载
        resetUploader()
      })
    },
    querySearch(queryString, cb) {
      console.log(queryString)
      this.$store.dispatch('user/getCityList', queryString).then(res => {
        this.cityList = res.map(x => {
          return {
            ...x,
            value: x.name.replace('市', '')
          }
        })
        cb(this.cityList)
      })
    },
    edit(i) {
      this.form = {
        ...this.$store.state.post.draftList[i]
      }
    },
    remove(i) {
      this.$store.commit('post/removedraftList', i)
    },
    // 草稿保存
    draftSave() {
      // 表单验证
      const flag = this.verification()
      if (flag != true) {
        return
      }
      this.$store.commit('post/setdraftList', this.form)
      this.form = {
        title: '',
        content: '',
        city: ''
      }
    },
    // 表单验证
    verification() {
      if (this.form.title.trim().length === 0) {
        return this.$message.error('标题不能为空')
      } else if (this.form.content.trim().length === 0) {
        return this.$message.error('内容不能为空')
      } else if (this.form.city.trim().length === 0) {
        return this.$message.error('请输入城市名称')
      }
      return true
    },
    // 发布
    async publish(){
      // 表单验证
      const flag = this.verification()
      if (flag != true) {
        return
      }
     const {data:res} =  await this.$axios({
       method:'POST',
        url:'/posts',
        headers:{'Authorization':'Bearer '+this.$store.state.user.userInfo.token},
        data:this.form
      })
      if(res.message==='新增成功'){
        this.$message.success('发布成功')
        this.form = {
        title: '',
        content: '',
        city: ''
      }
      }
    }
  },
  computed: {
    mytime() {
      var time = +new Date()
      return moment(time).format('YYYY-MM-DD')
    }
  }
}
</script>
<style lang="less" scoped>
.container {
  width: 1000px;
  min-width: 1000px;
  margin: 0 auto;
  display: flex;
  padding-top: 20px;
}
.left {
  flex: 1;
  h3 {
    font-size: 20px;
    font-weight: 400;
    height: 40px;
    line-height: 40px;
  }
  p {
    font-size: 12px;
    color: #666;
    height: 35px;
    line-height: 35px;
  }
  .el-button {
    margin-right: 10px;
  }
  .draftSave {
    color: #ffa500;
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
}
.right {
  width: 225px;
  margin-left: 30px;
  // background:red;
  .draft {
    border: 1px solid #ddd;
    padding: 15px 10px;
    h3 {
      font-size: 18px;
      font-weight: 300;
      margin-bottom: 10px;
    }
    .item {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      margin-bottom: 10px;
      .item_l {
        display: flex;
        flex-direction: column;
        span {
          color: #666;
        }
      }
    }
  }
}
.vue-editor {
  height: 458px;
}
</style>